<template>
  <div class="property-fee-container">
    <div class="page-header bg-white p-4 rounded-lg shadow-sm mb-4">
      <h1 class="text-xl font-bold text-gray-800">业主管理</h1>
      <p class="text-gray-500 mt-1">查看和管理所有住户房屋情况</p>
    </div>
    <div class="data-table-wrapper bg-white p-4 rounded-lg shadow-sm">
      <!-- 添加条件判断，确保数据获取成功后再渲染DataTable组件 -->
      <DataTable
        v-if="tableData.length > 0 && columns.length > 0"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @row-add="handleRowAdd"
        @row-edit="handleRowEdit"
        @row-delete="handleRowDelete"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        @sort-change="handleSortChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, type Ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import DataTable from '../components/common/FyyDataTable2.vue'
import formatPhoneNumber from '@/utils/formatDate.js';

// 类型定义
interface Owner {
  id: number
  name: string
  gender: '男' | '女'
  age: number
  tel: string
  dueDate: string
  comments?: string
}

// 分页结果类型（与Spring Boot后端保持一致）
interface PageResult<T> {
  content: T[]
  totalElements: number
  totalPages: number
  number: number
  size: number
  numberOfElements: number
  first: boolean
  last: boolean
}

// 列配置
const columns = [
  { prop: 'id', label: '业主ID', width: '80', sortable: true },
  { prop: 'name', label: '业主' },
  { prop: 'gender', label: '性别' },  
  { prop: 'age', label: '年龄' },    
  { 
    prop: 'tel', 
    label: '联系方式',
    formatter: (value: string) => formatPhoneNumber(value)
  },  
  { 
    prop: 'dueDate', 
    label: '入住时间', 
    type: 'date', 
    sortable: true,
    formatter: (value: string) => new Date(value).toLocaleDateString()
  },
]

// 状态管理
const tableData: Ref<Owner[]> = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10) 
const router = useRouter()

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 10000
})

// 获取业主数据
const fetchOwners = async (page: number = 1, size: number = 10, sortBy?: string, sortOrder?: string) => {
  loading.value = true
  try {
    const params: any = {
      page: page - 1,  
      size: size 
    }
    
    if (sortBy && sortOrder) {
      params.sort = `${sortBy},${sortOrder}`
    }
    
    const response = await api.get<PageResult<Owner>>('/owners', { params })
    console.log('执行到这一步ownerlist---00000000001')
    tableData.value = response.data.content
    total.value = response.data.totalElements
    currentPage.value = page
    pageSize.value = size 
    
    return response.data
  } catch (error) {
    console.error('获取业主数据失败', error)
    showErrorToast('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 事件处理器
const handleRowAdd = async (row: Partial<Owner>) => {
  try {
    const response = await api.post('/owners', {
      name: row.name,
      gender: row.gender,
      age: row.age,
      tel: row.tel,
      dueDate: row.dueDate,
      comments: row.comments
    })
    
    tableData.value.push(response.data)
    showSuccessToast('业主添加成功')
  } catch (error) {
    showErrorToast('业主添加失败')
  }
}

const handleRowEdit = async (row: Owner) => {
  try {
    await api.put(`/owners/${row.id}`, {
      name: row.name,
      gender: row.gender,
      age: row.age,
      tel: row.tel,
      dueDate: row.dueDate,
      comments: row.comments
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      tableData.value[index] = { ...row }
      showSuccessToast('业主信息更新成功')
    }
  } catch (error) {
    showErrorToast('业主信息更新失败')
  }
}

const handleRowDelete = async (row: Owner) => {
  const confirmDelete = await showConfirmDialog({
    title: '确认删除',
    message: `确定要删除业主 ${row.name} 的信息吗？`,
    confirmText: '删除',
    cancelText: '取消'
  })
  
  if (!confirmDelete) return
  
  try {
    await api.delete(`/owners/${row.id}`)
    
    tableData.value = tableData.value.filter(item => item.id !== row.id)
    showSuccessToast('业主信息已删除')
  } catch (error) {
    showErrorToast('删除失败，请重试')
  }
}

// 分页和排序事件处理
const handlePageChange = (page: number) => {
  fetchOwners(page, pageSize.value) 
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size 
  fetchOwners(currentPage.value, size) 
}

const handleSortChange = (sortBy: string, sortOrder: string) => {
  fetchOwners(currentPage.value, pageSize.value, sortBy, sortOrder)
}

onMounted(() => {
  fetchOwners()
})

// 模拟UI反馈函数
const showSuccessToast = (message: string) => {
  console.log('[Success]', message)
  // 实际项目中应调用UI库的toast组件111

}

const showErrorToast = (message: string) => {
  console.log('[Error]', message)
  // 实际项目中应调用UI库的toast组件
}

const showConfirmDialog = async (options: { 
  title: string, 
  message: string, 
  confirmText?: string, 
  cancelText?: string 
}) => {
  // 实际项目中应调用UI库的对话框组件
  return window.confirm(`${options.title}\n${options.message}`)
}
</script>